﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using BusinessLogic;
using System.Data.SqlClient;
using System.Data;
using System.Web.Security;

namespace DataAccessLogic
{
    public static class FormattedCodeTableDataAccess
    {
        #region Methods
        public static T BindRowToFormattedCodeTable<T>(DataRow row) where T : FormattedCodeTable<T>, new()
        {
            T t = CodeTableDataAccess.BindRowToCodeTable<T>(row);
            t.Abbreviation = DataAccess.CheckForStringColumn(row, "ABBREVIATION");

            return t;
        }

        public static Guid Create(string storedProcedure, string description, string abbreviation)
        {
            Guid id = Guid.Empty;
            Guid providerUserKey = new Guid(Membership.GetUser().ProviderUserKey.ToString());
            string outputParameterName = "@ID";

            if ((!string.IsNullOrWhiteSpace(description)) && (!string.IsNullOrWhiteSpace(abbreviation)))
            {
                SqlParameter p = new SqlParameter();
                p.ParameterName = outputParameterName;
                p.Direction = ParameterDirection.Output;
                p.DbType = DbType.Guid;

                List<SqlParameter> parms = new List<SqlParameter>();
                parms.Add(p);
                parms.Add(new SqlParameter("@DESCRIPTION", description));
                parms.Add(new SqlParameter("@ASPNETDBUSERID", providerUserKey));
                parms.Add(new SqlParameter("@ABBREVIATOIN", abbreviation));

                object obj = DataAccess.Create(storedProcedure, outputParameterName, parms);

                if (obj != null)
                {
                    id = new Guid(obj.ToString());
                }
            }

            return id;
        }

        public static void Delete(string storedProcedure, Guid id)
        {
            if (id != Guid.Empty)
            {
                DataAccess.Delete(storedProcedure, id);
            }
        }

        public static DataTable GetAll(string storedProcedure)
        {
            return DataAccess.Get(storedProcedure);
        }

        public static DataRow GetByID(string storedProcedure, Guid id)
        {
            DataRow dr = null;

            if(id != Guid.Empty)
            {
                List<SqlParameter> parms = new List<SqlParameter>();
                parms.Add(new SqlParameter("@ID", id));

                DataTable dt = DataAccess.Get(storedProcedure, parms);
            
                if ((dt != null) && (0 < dt.Rows.Count))
                {
                    dr = dt.Rows[0];
                }
            }

            return dr;
        }
        #endregion
    }
}